package com.topscomm.appv2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.topscomm.basic.util.PrimaryKeyUtil;
import com.topscomm.tap.TapService;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import com.topscomm.cbo.pojo.CboItemDetailsEntity;
import com.topscomm.cbo.pojo.CboRoleEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.pojo.CboUserRoleEntity;
import com.topscomm.cbo.service.impl.CboItemDetailsService;
import com.topscomm.cbo.service.impl.CboRoleService;
import com.topscomm.cbo.service.impl.CboUserRoleService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;

@SuppressWarnings("rawtypes")
public class Appv2Service<T extends Appv2Entity, TDao extends IAppv2Dao> extends TapService<T, TDao> implements IAppv2Service<T, TDao> {
    @Autowired
    private CboRoleService cboRoleService;
    @Autowired
    private CboUserRoleService cboUserRoleService;
    @Autowired
    private CboUserService cboUserService;
    @Autowired
    public CboItemDetailsService cboItemDetailsService;
    @Resource(name = "ehrSqlSessionTemplate")
    private SqlSessionTemplate ehrSqlSessionTemplate;
    @Resource(name = "mpmSqlSessionTemplate")
    private SqlSessionTemplate mpmSqlSessionTemplate;
    @Resource(name = "mmsSqlSessionTemplate")
    private SqlSessionTemplate mmsSqlSessionTemplate;
    @Resource(name = "meetSqlSessionTemplate")
    private SqlSessionTemplate meetSqlSessionTemplate;
    @Resource(name = "pmSqlSessionTemplate")
    private SqlSessionTemplate pmSqlSessionTemplate;
    @Resource(name = "cdmcSqlSessionTemplate")
    private SqlSessionTemplate cdmcSqlSessionTemplate;
    @Resource(name = "iscSqlSessionTemplate")
    private SqlSessionTemplate iscSqlSessionTemplate;
    @Resource(name = "oaSqlSessionTemplate")
    private SqlSessionTemplate oaSqlSessionTemplate;
    @Resource(name = "biSqlSessionTemplate")
    private SqlSessionTemplate biSqlSessionTemplate;
    @Resource(name = "scmSqlSessionTemplate")
    private SqlSessionTemplate scmSqlSessionTemplate;
    @Resource(name = "winSqlSessionTemplate")
    private SqlSessionTemplate winSqlSessionTemplate;
    @Resource(name = "erSqlSessionTemplate")
    private SqlSessionTemplate erSqlSessionTemplate;
    @Resource(name = "crmSqlSessionTemplate")
    private SqlSessionTemplate crmSqlSessionTemplate;
    @Resource(name = "hrSqlSessionTemplate")
    private SqlSessionTemplate hrSqlSessionTemplate;
    @Resource(name = "mspSqlSessionTemplate")
    private SqlSessionTemplate mspSqlSessionTemplate;
    @Resource(name = "omsSqlSessionTemplate")
    private SqlSessionTemplate omsSqlSessionTemplate;
    @Resource(name = "scrmfSqlSessionTemplate")
    private SqlSessionTemplate scrmfSqlSessionTemplate;
    public void SyncRoleAndUserRole(String syncSys, SqlSessionTemplate syncTemplate) {
        StringBufferProxy sql = new StringBufferProxy();
        String syncSysModule= "syncSysModule";
        if ("crm".equals(syncSys)) {
            syncSysModule= "syncCrmModule";
        }
        Map<String,Object> paramMap = new HashMap<>();
        // 获取系统同步时间
        sql.appendSingle(" itemid = (select id from cboitems where code = 'AppSysModuleList') and name = '{0}' ",syncSys);
        List<CboItemDetailsEntity> cboItemDetailsEntities = cboItemDetailsService.queryByWhere(sql.toString());
        sql.clear();
        if(cboItemDetailsEntities.size()==0) {
            return ;
        }
        // 系统简称
        String syscode = ConvertUtil.convertToString(cboItemDetailsEntities.get(0).getCode());
        // 同步时间
        String time = ConvertUtil.convertToString(cboItemDetailsEntities.get(0).getName());
        // 获取时间段内的角色变化
        paramMap.put("time", time);
        List<Map<String, Object>> oldrolelist = syncTemplate.selectList(syncSysModule+".queryRecentRole", paramMap);
        // 如果这段时间内角色有变化，进行新增或更新
        if(oldrolelist.size()>0) {
            for(Map<String, Object> map : oldrolelist) {
                String oldid = ConvertUtil.convertToString(map.get("id"));
                // 查找是否有这个角色
                sql.clear();
                sql.appendSingle("EXTENDFIELD9 = '{0}'",ConvertUtil.convertToString(map.get("id")));
                List<CboRoleEntity> cboRoleEntities = cboRoleService.queryByWhere(sql.toString());
                if(cboRoleEntities.size()>0) {
                    // 如果没有就新增
                    changeRole(map,syscode,"insert",syncSys);
                } else {
                    // 如果有就更新
                    changeRole(map,syscode,"update",syncSys);
                }
            }
        }
        // 查找系统的角色数量，与本系统对比是否一致
        oldrolelist = syncTemplate.selectList(syncSysModule+".queryAllRole", paramMap);
        sql.appendSingle("EXTENDFIELD10 = '{0}'",syncSys);
        List<CboRoleEntity> rolelist = cboRoleService.queryByWhere(sql.toString());
        // 角色个数不相同--权限中心大于旧系统角色人员人数  说明旧系统角色人员人数有删除的，需要遍历删除
        if(rolelist.size() > oldrolelist.size()) {
            List<String> list = new ArrayList<String>();
            for(Map<String, Object> map : oldrolelist) {
                String id = ConvertUtil.convertToString(map.get("id"));
                list.add(id);
            }
            StringBuffer delids = new StringBuffer();
            for(CboRoleEntity roleEntity : rolelist) {
                String oldSysId = ConvertUtil.convertToString(roleEntity.getExtendfield9());
                if(!list.contains(oldSysId)) {
                    delids.append("'").append(oldSysId).append("',");
                }
            }
            if(delids.toString().length()>0) {
                cboRoleService.deleteByIds(delids.toString().substring(0,delids.toString().length()-1));
            }
        }
        // 角色人员处理
        // 查找角色人员表中在time时间内修改的所有数据。
        List<Map<String, Object>> olduserrolelist = syncTemplate.selectList(syncSysModule+".queryRecentUserRole", paramMap);
        if(oldrolelist.size()>0) {
            for(Map<String, Object> map : olduserrolelist) {
                String oldsysid = ConvertUtil.convertToString(map.get("id"));
                String oldsysroleid = ConvertUtil.convertToString(map.get("roleid"));
                sql.clear();
                // 本系统该角色人员对应的角色
                sql.appendSingle("EXTENDFIELD9 = '{0}' and EXTENDFIELD10 = '{1}'",oldsysroleid,syscode);
                List<CboRoleEntity> cboRoleEntities = cboRoleService.queryByWhere(sql.toString());
                sql.clear();
                sql.appendSingle("DESCRIPTION = '{0}'",syscode+oldsysid);
                // 如果本系统没有对应角色
                if(cboRoleEntities.size()==0){
                    // 如果本系统没有对应角色，删除这个角色人员
                    cboUserRoleService.deleteByWhere(sql.toString());
                    continue;
                }
                // 本系统该角色人员对应的角色的id
                long newsysroleid = cboRoleEntities.get(0).getId();
                // 查找本系统是否有这个角色人员----
                List<CboUserRoleEntity> userRoleEntities = cboUserRoleService.queryByWhere(sql.toString());
                if(userRoleEntities.size()>0) {
                    // 如果有就更新
                    changeUserRole(map,syscode,"update",syncTemplate,syncSysModule,userRoleEntities.get(0).getDescription(),newsysroleid);
                } else {
                    // 如果没有就新增
                    changeUserRole(map,syscode,"insert",syncTemplate,syncSysModule,"",newsysroleid);
                }
            }
        }
        // 查找系统的角色人员数量，与本系统对比是否一致
        olduserrolelist = syncTemplate.selectList(syncSysModule+".queryAllUserRole", paramMap);
        sql.clear();
        sql.appendSingle("ROLEID IN (SELECT id FROM CBOROLE WHERE EXTENDFIELD10 = '{0}')",syncSys);
        List<CboUserRoleEntity> userrolelist = cboUserRoleService.queryByWhere(sql.toString());
        // 角色个数不相同--权限中心大于旧系统角色人员人数  说明旧系统角色人员人数有删除的，需要遍历删除
        if(userrolelist.size() > olduserrolelist.size()) {
            List<String> list = new ArrayList<>();
            for(Map<String, Object> map : olduserrolelist) {
                String oldFlag = ConvertUtil.convertToString(syscode+map.get("id"));
                list.add(oldFlag);
            }
            StringBuffer delFlags = new StringBuffer();
            for(CboUserRoleEntity userRoleEntity : userrolelist) {
                String flag = ConvertUtil.convertToString(userRoleEntity.getDescription());
                if(!list.contains(flag)) {
                    delFlags.append("'").append(flag).append("',");
                }
            }
            if(delFlags.toString().length()>0) {
                cboUserRoleService.deleteByIds(delFlags.toString().substring(0,delFlags.toString().length()-1));
            }
        }
        return;
    }

    private void changeRole(Map<String, Object> map,String sys,String changetype,String syncSys) {
        CboRoleEntity cboRoleEntity = new CboRoleEntity();
//        String newroleid = number+map.get("id");
//        cboRoleEntity.setId(ConvertUtil.convertToLong(newroleid));
        long roleid = PrimaryKeyUtil.GeneIDs(cboRoleEntity.getTableName(), 1)[0];
        cboRoleEntity.setId(roleid);
        cboRoleEntity.setCode(ConvertUtil.convertToString(map.get("code")));
        cboRoleEntity.setName(ConvertUtil.convertToString((syncSys)+map.get("name")));
        cboRoleEntity.setOrgid(ConvertUtil.convertToLong(map.get("orgid")));
        cboRoleEntity.setCategory(ConvertUtil.convertToString(map.get("category")));
        cboRoleEntity.setIsvisible(ConvertUtil.convertToInt(map.get("isvisible")));
        cboRoleEntity.setExtendfield1(ConvertUtil.convertToString(map.get("extendfield1")));
        cboRoleEntity.setExtendfield2(ConvertUtil.convertToString(map.get("extendfield2")));
        cboRoleEntity.setExtendfield3(ConvertUtil.convertToString(map.get("extendfield3")));
        cboRoleEntity.setExtendfield4(ConvertUtil.convertToString(map.get("extendfield4")));
        cboRoleEntity.setExtendfield5(ConvertUtil.convertToString(map.get("extendfield5")));
        cboRoleEntity.setExtendfield6(ConvertUtil.convertToString(map.get("extendfield6")));
        cboRoleEntity.setExtendfield7(ConvertUtil.convertToString(map.get("extendfield7")));
        cboRoleEntity.setExtendfield8(ConvertUtil.convertToString(map.get("extendfield8")));
        cboRoleEntity.setExtendfield9(ConvertUtil.convertToString(map.get("id")));
        cboRoleEntity.setExtendfield10(sys);
        cboRoleEntity.setSortCode(ConvertUtil.convertToInt(map.get("sortcode")));
        cboRoleEntity.setDescription(ConvertUtil.convertToString(map.get("description")));
        cboRoleEntity.setEnabled(ConvertUtil.convertToInt(map.get("enabled")));
        if(changetype.equals("insert")) {
            cboRoleService.insert(cboRoleEntity);
        } else {
            cboRoleService.updateEntity(cboRoleEntity);
        }
    }

    private void changeUserRole(Map<String, Object> map,String sys,String changetype,
                                SqlSessionTemplate syncTemplate, String syncSysModule,String newsysid, long newsysroleid) {
        CboUserRoleEntity cbouserRoleEntity = new CboUserRoleEntity();
        // 原系统id
        String oldSysId = ConvertUtil.convertToString(map.get("id"));
        Map<String,Object> paramMap = new HashMap<>();
        // 原系统人员
        paramMap.put("userid", map.get("userid"));
        // 查找原系统有没有这个人
        List<Map<String, Object>> user = syncTemplate.selectList(syncSysModule+".queryUser", paramMap);
        if(user==null || user.size()==0) {
            return;
        }
//        cbouserRoleEntity.setId(ConvertUtil.convertToLong(newid));
        // 查找本系统这个人的信息
        StringBufferProxy sql = new StringBufferProxy();
        sql.clear();
        sql.appendSingle("code = '{0}'", user.get(0).get("code"));
        List<CboUserEntity> cboUserEntities = cboUserService.queryByWhere(sql.toString());
        if(cboUserEntities == null || cboUserEntities.size()==0) {
            return;
        }
        // 将原系统的代号_id放到备注里
        cbouserRoleEntity.setDescription(sys+oldSysId);
        // 赋值转换过来的人
        cbouserRoleEntity.setUserid(ConvertUtil.convertToLong(cboUserEntities.get(0).getId()));
        // 赋值本系统对应的人员
        cbouserRoleEntity.setRoleid(ConvertUtil.convertToLong(newsysroleid));
        if(changetype.equals("insert")) {
            long userroleid = PrimaryKeyUtil.GeneIDs(cbouserRoleEntity.getTableName(), 1)[0];
            cbouserRoleEntity.setId(userroleid);
            cboUserRoleService.insert(cbouserRoleEntity);
        } else {
            cbouserRoleEntity.setId(ConvertUtil.convertToLong(newsysid));
            cboUserRoleService.updateEntity(cbouserRoleEntity);
        }
    }
}
